package com.算法.软件设计与开发.试题编号_2_1_12_中国结图案打印系统关键算法;

import java.io.*;
import java.util.Scanner;

public class 任务三_打印中国结图案关键算法 {
    /**
     * 由于中国结的形状是菱形图案，所以现在公司需要设计一个打印菱形的方
     * 法。
     * 从键盘输入一个整数 N，打印出有 N*2-1 行的菱形。
     * 例如输入整数 4，则屏幕输出如下菱形，并同时写入 Shape.txt。
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入菱形的行数：");
        int rows = input.nextInt();

        int n = rows/2+2 ;
        for (int i = 1; i <= n-1; i++) {
            for (int j = 1; j <= n - i; j++) {
                System.out.print(" ");
                String s = " ";
                byte[] bytes = s.getBytes();
                saveFile("d:\\Shape.txt",bytes);
            }
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
                String s = "*";
                byte[] bytes = s.getBytes();
                saveFile("d:\\Shape.txt",bytes);
            }
            System.out.print("\n");
        }
        for (int i = rows; i >= 1; i--) {
            for (int j = 1; j <= n - i; j++) {
                System.out.print(" ");
                String s = " ";
                byte[] bytes = s.getBytes();
                saveFile("d:\\Shape.txt",bytes);
            }
            for (int k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
                String s = "*";
                byte[] bytes = s.getBytes();
                saveFile("d:Shape.txt",bytes);
            }
            System.out.print("\n");
            String s = "\n";
            byte[] bytes = s.getBytes();
            saveFile("d:\\Shape.txt",bytes);
        }
    }

    public static boolean saveFile(String filename,byte[] bytes){
        OutputStream outputStream = null;
        try {
            File file = new File(filename);
            File parent = file.getParentFile();
            if( !parent.exists() && !parent.mkdirs()){
                return false;
            }
            outputStream = new FileOutputStream(file);
            outputStream.write(bytes);
            outputStream.flush();
            return true;
        }catch (FileNotFoundException e){
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            if (outputStream != null) {
                try{
                    outputStream.close();
                }catch (IOException e) {}
            }
        }
    }
}
